package simple.form.controller;

import simple.form.utils.SafeConvertUtil;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 请求
 * Created by Administrator on 2017/2/24.
 */
public class Request {

    private HttpServletRequest request;
    private Map<String,String> param = new HashMap<>();


    public Request(ServletRequest request) {
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = SafeConvertUtil.toString(paramNames.nextElement());
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = SafeConvertUtil.toString(paramValues[0]);
                param.put(paramName,paramValue);
            }
        }
        this.request = (HttpServletRequest) request;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(ServletRequest request) {
        this.request = (HttpServletRequest) request;
    }

    public String getParamString(){
        StringBuilder paramString = new StringBuilder();
        Iterator iter = param.entrySet().iterator();

        int index =1;
        int size = param.size();
        while (iter.hasNext()){
            Map.Entry entry = (Map.Entry) iter.next();
            String key = SafeConvertUtil.toString(entry.getKey());
            String val = SafeConvertUtil.toString(entry.getValue());
            if(index++==size){
                paramString.append(String.format("\"%s\":\"%s\"",key,val));
            }else{
                paramString.append(String.format("\"%s\":\"%s\",",key,val));
            }

        }
        return "{"+paramString.toString()+"}";
    }
}
